package com.kll.tv.views.fragment.main

import android.content.Intent
import android.view.Gravity
import android.view.View
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.kll.carolinehmibiz.OperationManager
import com.kll.carolinehmibiz.model.AccountModel
import com.kll.carolinehmibiz.model.OperateListener
import com.kll.carolinehmibiz.net.bean.GetUserInfoResponse
import com.kll.carolinehmibiz.net.bean.RefreshTokenResponse
import com.kll.carolinehmibiz.presentation.listener.MainUcenterProtocol
import com.kll.carolinehmibiz.presentation.presenter.MainUcenterPresenter
import com.kll.carolinehmibiz.base.utils.L
import com.kll.tv.R
import com.kll.tv.base.views.MainBaseFragment
import com.kll.tv.databinding.FragmentMainUcenterBinding
import com.kll.tv.utils.*
import com.kll.tv.views.MyAppointmentActivity
import com.kll.tv.views.MyHarvestAddressActivity
import com.kll.tv.views.adapter.PersonalAvatarPopAdapter
import com.kll.tv.views.adapter.PersonalSexPopAdapter
import com.kll.tv.views.ui.pickerview.builder.TimePickerBuilder
import com.kll.tv.views.ui.pickerview.listener.OnTimeSelectListener
import com.luck.picture.lib.PictureSelector
import com.luck.picture.lib.config.PictureConfig
import com.luck.picture.lib.config.PictureMimeType
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.listener.OnResultCallbackListener
import java.io.File
import java.text.SimpleDateFormat
import java.util.*


/**
 * ====================================================
 * Created by Ziliang Cai on 2021/12/7 22:19
 * <a href="mailto:752777456@qq.com">Contact me</a>
 * ====================================================
 */
class MainUcenterFragmengt: MainBaseFragment<MainUcenterPresenter>(), MainUcenterProtocol.IView {
    private lateinit var binding: FragmentMainUcenterBinding
    private var popAvatarWindow: PopWindow? = null
    private var popSexWindow: PopWindow? = null
    private var personalAvatarPopAdapter: PersonalAvatarPopAdapter? = null
    private var personalSexPopAdapter: PersonalSexPopAdapter? = null
    private var time = ""
    private var getUserInfoResponse: GetUserInfoResponse? = null

    override fun createPresenter(): MainUcenterPresenter {
        return MainUcenterPresenter(requireContext(), this)
    }

    override fun initViewBinding(): View {
        binding = FragmentMainUcenterBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun init() {
        mPresenter.getUser()

        initListener()
    }

    private fun initListener() {
        // 头像
        binding.tvHead.setOnClickListener {
            toShowAvatarPop()
        }
        // 姓名
        binding.tvName.setOnClickListener {
            // startActivity(Intent(context, UpdateNameActivity::class.java))
        }
        // 性别
        binding.tvSex.setOnClickListener {
            toShowSexPop()
        }
        // 年龄
        binding.tvAge.setOnClickListener {
            initTimePicker()
        }
        // 健康档案
        binding.tvHealthyFiles.setOnClickListener {
            AppToast.show("敬请期待！", 2000)
        }
        // 我的收货地址
        binding.tvMyHarvestAddress.setOnClickListener {
            startActivity(Intent(context, MyHarvestAddressActivity::class.java))
        }
        // 我的预约
        binding.tvMyAppointment.setOnClickListener {
            startActivity(Intent(context, MyAppointmentActivity::class.java))
        }
    }

    private fun refreshUI(data: GetUserInfoResponse) {

        var avatar = if(data.head_pic.isNotEmpty() && data.head_pic.indexOf("?") > 0) data.head_pic.substring(0, data.head_pic.indexOf("?")) else ""

        L.d("TAG", "refreshUI: $avatar}")
        Glide.with(this).load("http://$avatar").apply(RequestOptions().centerCrop()).into(binding.ivHead)
        binding.tvNameValue.text = data.username
        if (data.sex == 1) {
            binding.tvSexValue.text = "男"
        } else if (data.sex == 2) {
            binding.tvSexValue.text = "女"
        } else {
            binding.tvSexValue.text = "未知"
        }
        binding.tvAgeValue.text = BirthdayToAgeUtil.BirthdayToAge(data.birthday)
    }

    // 弹窗
    private var toShowAvatarPopIsBusying = false
    private fun toShowAvatarPop() {
        if (toShowAvatarPopIsBusying) return
        toShowAvatarPopIsBusying = true

        if (popAvatarWindow == null) {
            popAvatarWindow = PopWindow(activity)
            personalAvatarPopAdapter = PersonalAvatarPopAdapter(requireContext(),
                View.OnClickListener { v ->
                    when(v.id) {
                        R.id.tv_photograph -> {
                            // 拍照
                            AppToast.show("拍摄", 2000)
                            getAndroidQCamera()
                        }
                        R.id.tv_from -> {
                            // 从电视选择
                            AppToast.show("从相册选择", 2000)
                            getAndroidQImage()
                        }
                        R.id.tv_cancel -> {
                            // 取消
                            AppToast.show("取消", 2000)
                        }
                    }
                    popAvatarWindow!!.dismiss()
                })
            popAvatarWindow!!.addView(personalAvatarPopAdapter)
            popAvatarWindow!!.animationStyle = R.style.popwindow_anim_style
        }
        popAvatarWindow!!.showAtLocation(binding.root, Gravity.BOTTOM, 0, 0)
        toShowAvatarPopIsBusying = false
    }

    /**
     * 适配AndroidQ的相册获取
     */
    private fun getAndroidQImage() {
        PictureSelector.create(this)
            .openGallery(PictureMimeType.ofImage()) // 全部-ofAll 图片-ofImage 视频-ofVideo 音频-ofAudio
            .loadImageEngine(GlideEngine.createGlideEngine())
            .isWeChatStyle(true)
            .maxSelectNum(1) // 最大图片选择数量
            .minSelectNum(1) // 最小图片选择数量
            .compress(false)
            .minimumCompressSize(1024)
            .imageSpanCount(4) // 每行显示个数
            .isReturnEmpty(false) // 未选择数据时点击按钮是否可以返回
            .enableCrop(true) // 是否裁剪
            .withAspectRatio(1, 1) // 裁剪比例，如16:9 3:2 3:4 1:1 可自定义
            .showCropFrame(true) // 是否显示裁剪矩形边框，圆形裁剪时建议设为 false
            .showCropGrid(true) // 是否显示裁剪矩形网格，圆形裁剪时建议设为false
            .selectionMode(PictureConfig.MULTIPLE) // 多选 or 单选
            .forResult(object : OnResultCallbackListener<LocalMedia> {
                override fun onResult(result: MutableList<LocalMedia>?) {
                    if (result != null && result.size > 0) {
                        L.d("TAG", "cutPath: ${File(result[0].cutPath)}")
                        mPresenter.uploadHeadImg(File(result[0].cutPath))
                    }
                }

                override fun onCancel() {
                    AppToast.show("操作已取消！", 2000)
                }

            })
    }

    /**
     * 拍照
     */
    private fun getAndroidQCamera() {
        PictureSelector.create(this)
            .openCamera(PictureMimeType.ofImage())
            .loadImageEngine(GlideEngine.createGlideEngine())
            .enableCrop(true) // 是否裁剪
            .withAspectRatio(1, 1) // 裁剪比例，如16:9 3:2 3:4 1:1 可自定义
            .showCropFrame(true) // 是否显示裁剪矩形边框，圆形裁剪时建议设为 false
            .showCropGrid(true) // 是否显示裁剪矩形网格，圆形裁剪时建议设为false
            .forResult(object : OnResultCallbackListener<LocalMedia> {
                override fun onResult(result: MutableList<LocalMedia>?) {
                    if (result != null && result.size != 0) {
                        L.d("TAG", "cutPath: ${File(result[0].cutPath)}")
                        mPresenter.uploadHeadImg(File(result[0].cutPath))
                    }
                }

                override fun onCancel() {
                    AppToast.show("操作已取消！", 2000)
                }

            })
    }

    // 弹窗
    private var toShowSexPopIsBusying = false
    private fun toShowSexPop() {
        if (toShowSexPopIsBusying) return
        toShowSexPopIsBusying = true

        if (popSexWindow == null) {
            popSexWindow = PopWindow(activity)
            personalSexPopAdapter = PersonalSexPopAdapter(requireContext(),
                View.OnClickListener { v ->
                    when(v.id) {
                        R.id.tv_nan -> {
                            // 男
                            getUserInfoResponse?.sex = 1
                            mPresenter.editUserInfo(getUserInfoResponse!!)
                        }
                        R.id.tv_nv -> {
                            // 女
                            getUserInfoResponse?.sex = 2
                            mPresenter.editUserInfo(getUserInfoResponse!!)
                        }
                        R.id.tv_cancel -> {
                            // 取消
                        }
                    }
                    popSexWindow!!.dismiss()
                })
            popSexWindow!!.addView(personalSexPopAdapter)
            popSexWindow!!.animationStyle = R.style.popwindow_anim_style
        }
        popSexWindow!!.showAtLocation(binding.root, Gravity.BOTTOM, 0, 0)
        toShowSexPopIsBusying = false
    }

    /**
     * 初始化时间选择器
     */
    private fun initTimePicker() { //Dialog 模式下，在底部弹出
        val timePicker =  TimePickerBuilder(context, OnTimeSelectListener { date, v ->
            binding.tvAge.setFocusable(true)
            binding.tvAge.requestFocus()
            binding.tvAge.setFocusableInTouchMode(true)
            binding.tvAge.requestFocusFromTouch()

            // 赋值
            time = getTime(date)!!

            getUserInfoResponse!!.birthday = time
            if (getUserInfoResponse != null) {
                mPresenter.editUserInfo(getUserInfoResponse!!)
            }
        })
            .setType(booleanArrayOf(true, true, true, false, false, false))
            .addOnCancelClickListener {
                binding.tvAge.setFocusable(true)
                binding.tvAge.requestFocus()
                binding.tvAge.setFocusableInTouchMode(true)
                binding.tvAge.requestFocusFromTouch()
            }
            .setItemVisibleCount(6) //若设置偶数，实际值会加1（比如设置6，则最大可见条目为7）
            .setLineSpacingMultiplier(2.0f)
            .isAlphaGradient(true)
            .setContentTextSize(30)
            .setTitleSize(30)
            .setSubCalSize(30)
            .setTitleText("请选择").isDialog(false)
            .setLabel("年","月","日","时","分","秒")
            .build()

        timePicker.show()
    }

    private fun getTime(date: Date): String? { //可根据需要自行截取数据显示
        val format = SimpleDateFormat("yyyy-MM-dd")
        return format.format(date)
    }

    /**
     * 获取个人信息成功
     */
    override fun getUserInfoSuccessed(data: GetUserInfoResponse) {
        getUserInfoResponse = data
        refreshUI(data)
    }

    /**
     * 获取个人信息失败
     */
    override fun getUserInfoFailed(code: Int, message: String) {
        AppToast.show(message, 2000)
        if (code == 102) {
            // token过期 刷新token
            OperationManager.getInstancce().refreshToken(object : OperateListener {
                override fun onSuccess(state: Int, obj: Any?) {
                    var data = obj as RefreshTokenResponse
                    AccountModel.getInstance(context!!).updateUserToken(data.token)
                    mPresenter.getUser()
                }

                override fun onFail(code: Int, message: String) {
                    AppToast.show(message, 2000)
                    if (code == 101) {
                        loginAgain()
                    }
                }

            })
        }
        if (code == 101) {
            loginAgain()
        }
    }

    /**
     * 修改个人信息成功
     */
    override fun editUserInfoSuccessed() {
        AppToast.show("修改个人信息成功！", 2000)
        mPresenter.getUser()
    }

    /**
     * 修改个人信息失败
     */
    override fun editUserInfoFailed(code: Int, message: String) {
        AppToast.show(message, 2000)
        if (code == 102) {
            // token过期 刷新token
            OperationManager.getInstancce().refreshToken(object : OperateListener {
                override fun onSuccess(state: Int, obj: Any?) {
                    var data = obj as RefreshTokenResponse
                    AccountModel.getInstance(context!!).updateUserToken(data.token)
                    mPresenter.editUserInfo(getUserInfoResponse!!)
                }

                override fun onFail(code: Int, message: String) {
                    AppToast.show(message, 2000)
                    if (code == 101) {
                        loginAgain()
                    }
                }

            })
        }
        if (code == 101) {
            loginAgain()
        }
    }

    /**
     * 上传头像成功
     */
    override fun uploadHeadImgSuccessed(path: String) {
        AppToast.show("上传头像成功！", 2000)
        if (getUserInfoResponse != null) {
            getUserInfoResponse!!.head_pic = path
            mPresenter.editUserInfo(getUserInfoResponse!!)
        }
    }

    /**
     * 上传头像失败
     */
    override fun uploadHeadImgFailed(code: Int, message: String) {
        AppToast.show(message, 2000)
        if (code == 102) {
            // token过期 刷新token
            OperationManager.getInstancce().refreshToken(object : OperateListener {
                override fun onSuccess(state: Int, obj: Any?) {
                    var data = obj as RefreshTokenResponse
                    AccountModel.getInstance(context!!).updateUserToken(data.token)
                }

                override fun onFail(code: Int, message: String) {
                    AppToast.show(message, 2000)
                    if (code == 101) {
                        loginAgain()
                    }
                }

            })
        }
        if (code == 101) {
            loginAgain()
        }
    }

}

fun String.substring() {
    if(this.isNotEmpty()) this.substring(0, this.indexOf("?")) else ""
}